package com.eoner.baselibrary.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.TextView;

@SuppressLint("AppCompatCustomView")
public class MyTextView extends TextView implements Runnable {

    String TAG = "MarqueeText";

    private int currentScrollX = 0;// 当前滚动的位置
    private int textWidth;
    private int viewWidth;
    private boolean isMeasure = false;
    private boolean isRoll = false;
    AgainListener againListener;

    public MyTextView(Context context) {
        super(context);
        init();
    }

    public MyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public MyTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    void init() {
        setGravity(Gravity.CENTER_VERTICAL);
        setSingleLine();
        setEllipsize(TextUtils.TruncateAt.MARQUEE);
        startScroll();
        addTextChangedListener(textWatcher);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (!isMeasure) {
            textWidth = getTextWidth();
            viewWidth = getWidth();
            isMeasure = true;
        }
    }

    TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            textWidth = getTextWidth();
        }
    };

    @Override
    public void run() {
        if (textWidth > viewWidth) {
            //需要滚动
            currentScrollX += 3;
            scrollTo(currentScrollX, 0);
            if (getScrollX() > textWidth) {
                againListener.Again();
                currentScrollX = -viewWidth;
                scrollTo(currentScrollX, 0);
            }
            postDelayed(this, 30);
        } else {
            //无需滚动
            scrollTo(0, 0);
            postDelayed(this, 500);
        }
    }

    public void startScroll() {
        post(this);
    }

    public void stopScroll() {
        this.removeCallbacks(this);
    }

    /**
     * 获取文字宽度
     */
    public int getTextWidth() {
        Paint paint = this.getPaint();
        String str = this.getText().toString();
        return (int) paint.measureText(str);
    }

    public void setAgainListener(AgainListener againListener) {
        this.againListener = againListener;
    }

    public interface AgainListener {
        void Again();
    }
}
